package com.huluobo.a2209mdmdemo.video

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import androidx.media3.common.MediaItem
import androidx.media3.common.Player.REPEAT_MODE_ONE
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import androidx.navigation.NavHostController
import com.google.gson.Gson
import com.huluobo.a2209mdmdemo.entity.VideoBeanItem
import com.huluobo.lib_http.Const
import com.tencent.mmkv.MMKV

/**
 *  Created by LC on 2025/3/6.
 *
 */
@Composable
fun VideoPage(navHostController: NavHostController) {
    //获取context
    val context = LocalContext.current
    //获取播放地址
    val videoUrl = MMKV.defaultMMKV().decodeString(Const.PARAM_VIDEO, "")
    //保存播放器的状态
    val exoPlayer = remember {
        //创建播放器
        ExoPlayer.Builder(context).build().apply {
            //设置播放路径
            setMediaItem(MediaItem.fromUri(videoUrl!!))
            //准备
            prepare()
            //设置当加载完毕后直接播放
            playWhenReady = true
            //重复模式,只播放一次
            repeatMode = REPEAT_MODE_ONE
        }
    }

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
    ) {
        AndroidView(factory = {
            //存放播放器的View
            PlayerView(context).apply {
                //指定播放器
                player = exoPlayer
                //使用默认的控制条
                useController = true
            }
        }, modifier = Modifier.fillMaxSize())
    }

    DisposableEffect(Unit) {
        onDispose {
            //当Compose组件被移除时,释放播放器,相当于Activity的OnDestroy
            exoPlayer.release()
        }
    }
}